package com.xinling.modules.taskflow.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.xinling.modules.chat.model.dto.ArkRequest;
import com.xinling.modules.chat.model.dto.ArkResponse;
import com.xinling.modules.taskflow.model.LLMDataPackage;
import com.xinling.modules.taskflow.service.LLMCallService;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: Lucas
 * @CreateTime: 2025-06-12
 * @Description:
 * @Version: 1.0
 */

@Service
@Slf4j
public class LLMCallServiceImpl implements LLMCallService {

    private static final Logger logger = LoggerFactory.getLogger(LLMCallServiceImpl.class);
    @Value("${ark.api.key}")
    private String arkApiKey;

    @Value("${ark.api.url}")
    private String arkApiUrl;

    //默认模型
    private static final String DEFAULT_MODEL = "deepseek-v3-250324";

    private final RestTemplate restTemplate;

    public LLMCallServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public ArkResponse callLLM(LLMDataPackage dataPackage, String model) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + arkApiKey);
        ArkRequest arkRequest = new ArkRequest();
        arkRequest.setModel(model);
        arkRequest.setMessages(dataPackage.getMessages());
        ArkResponse response = new ArkResponse();
        if(StringUtils.isEmpty(model)){
            logger.error("模型不能为空");
            return new ArkResponse();
        }else{
            logger.info("调用LLM模型: {}", model);
            logger.debug("请求参数: {}", arkRequest);
            response = restTemplate.postForObject(
                    arkApiUrl + "chat/completions",
                    new HttpEntity<>(arkRequest, headers),
                    ArkResponse.class
            );
            logger.debug("响应结果: {}", response);
            logger.info("LLM调用成功，返回内容: {}", response.getChoices().get(0).getMessage().getContent());
        }
        return null;
    }

    @Override
    public ArkResponse callLLM(LLMDataPackage dataPackage) {
        return callLLM(dataPackage, DEFAULT_MODEL);
    }
}
